package com.jy.api.controller.clerk;

import com.jy.api.dao.EmployeeDao;
import com.jy.api.dao.WorkShiftDao;
import com.jy.api.domain.*;
import com.jy.api.service.OrderService;
import com.jy.api.service.WorkshiftService;
import com.jy.api.util.MyDateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lihu on 2017/12/25.
 */
@Slf4j
@RestController
@RequestMapping(value = "v1/clerk/", produces = "application/json;charset=utf-8")
public class ClerkWorkShiftController {


    @Autowired
    WorkshiftService workshiftService;


    @Autowired
    WorkShiftDao workShiftDao;

    @Autowired
    OrderService orderService;
    private JdbcTemplate jdbc;
    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    public void setJdbc(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }


    /**
     * 获取当前收银员在当前店铺交班信息
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "workshift/{storeId}/list")
    public ResponseEntity getWorkeShifts(@PathVariable(name = "storeId") String storeId,
                                         Principal principal) {
        try {
            return ResponseEntity.ok(workshiftService.getStaffInfo(principal.getName(), storeId));
        } catch (Exception ex) {
            log.error("getWorkeShifts is error==> storeId:{},principal:{}", storeId, principal, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }


    @GetMapping("get-work")
    public ResponseEntity getTodayWork(@RequestParam("userName") String userName, @RequestParam("storeId") String storeId, @RequestParam("time") String time) {
        BeanPropertyRowMapper item = new BeanPropertyRowMapper<>(EmployeeKPIItem.class);
        item.setPrimitivesDefaultedForNullValue(true);
        EmployeeKPI kpi = new EmployeeKPI();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        Date startDate = null;
        Date endDate = null;
        try {
            startDate = MyDateUtils.getEarliest(sdf.parse(time));
            endDate = MyDateUtils.getLastest(sdf.parse(time));
        } catch (ParseException e) {
            log.info("时间转换异常");
        }
        List<EmployeeKPIItem> nowSalesItemDetails = jdbc.query("SELECT SUM(oi.`quantity`) AS qty , SUM(oi.`deal_price`) AS amount , p.`parent_type_name` AS typeName FROM `order_item` oi LEFT JOIN `product` p on oi.`product_id`= p.`id` WHERE `order_id` IN(SELECT `id` FROM `order` o WHERE `store_id`=?  AND `creator_id`=?  AND o.`payment_time`> ?   AND o.`payment_time`<= ?  AND `enabled`= 1 AND o.`status` IN('UNFINISHED', 'FINISHED') AND `enabled`= 1)  AND oi.`enabled`= 1 GROUP BY p.`parent_type_name`  ORDER BY amount DESC "
                , item, storeId, userName, startDate, endDate);
        double a = 0.0;
        for (EmployeeKPIItem kpiItem : nowSalesItemDetails) {
            a += kpiItem.getAmount();
            if (null == kpiItem.getTypeName() || kpiItem.getTypeName().equals("")) {
                kpiItem.setTypeName("会员充值");
            }
        }
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);
        nf.setGroupingUsed(false);
        kpi.setAmount(Double.valueOf(nf.format(a)));
        kpi.setQty(0);
        kpi.setTarget(0);
        kpi.setItems(nowSalesItemDetails);
        return ResponseEntity.ok(kpi);
    }


    /**
     * 获取当前班次详情
     *
     * @param id
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "workshift/{id}/details")
    public ResponseEntity getWorkshiftDetails(@PathVariable(name = "id") String id) {
        WorkShift workShift = workShiftDao.findOne(id);
        if (workShift == null) {
            return new ResponseEntity("查询失败当前交班信息不存在！", HttpStatus.BAD_REQUEST);
        }
        try {
            return ResponseEntity.ok(workshiftService.getWorkShiftDetails(workShift));
        } catch (Exception ex) {
            log.error("getWorkshiftDetails is error=>id:{}", id, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);

        }
    }


    /**
     * 获取当前班次详情
     *
     * @param id
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "workshift/{id}/orders-list")
    public ResponseEntity getWorkshiftOrderDetails(@PathVariable(name = "id") String id,
                                                   @PageableDefault(value = 10, sort = {"paymentTime"}, direction = Sort.Direction.ASC) Pageable pageable) {
        WorkShift workShift = workShiftDao.findOne(id);
        if (workShift == null) {
            return new ResponseEntity("查询失败当前交班信息不存在！", HttpStatus.BAD_REQUEST);
        }
        try {
            return ResponseEntity.ok(orderService.getOrderUntreated(workShift, pageable));
        } catch (Exception ex) {
            log.error("getWorkshiftDetails is error=>id:{}", id, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);

        }
    }


}
